
<template>
  <div class="create-post-page container">
    <h4>{{ isEditMode ? '编辑文章' : '新建文章' }}</h4>

    <Uploader action='/upload'
              class="d-flex justify-content-center align-items-center bg-light text-secondary w-100 my-4"
              :beforeUpload="commonUploadCheck"
              @file-uploaded="onFileUpload"
              @file-uploaded-error="onFileUploadedError"
              @file-uploaded-delete="onFileUploadedDelete"
              :uploaded="uploadedData">
      <!-- (slot特殊性)子slot给的值是哪个name就拿哪个name #uploaded="dataProps"-->
      <h2>点击上传图片</h2>

      <template #loading>
        <div class="d-flex">
          <div class="spinner-border text-secondary"
               role="status">
            <span class="visually-hidden">loading...</span>
          </div>
          <h2>正在上传</h2>
        </div>
      </template>

      <template #uploaded="dataProps">
        <div class="uploaded-area">
          <img :src="dataProps.uploadedData.data.url"
               alt="预览图">
          <h3>点击重新上传</h3>
        </div>
      </template>
    </Uploader>

    <ValidateFrom @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">文章标题</label>
        <ValidateInput :rules="titleRules"
                       v-model="titleVal"
                       placeholder="请输入文章标题"
                       type="text">
        </ValidateInput>
      </div>
      <div class="mb-3">
        <label class="form-label">文字详情</label>

        <editor v-model="contentVal"
                :options="editorOptions"
                @blur="checkEditor"
                :class="{ 'is-invalid': !editorStatus.isValid }">
        </editor>
        <span v-if="!editorStatus.isValid"
              class="invalid-feedback mt-1">{{ editorStatus.message }}</span>
      </div>
      <template #submit>
        <button class="btn btn-primary btn-large">{{ isEditMode ? '编辑文章' : '发表文章' }}</button>
      </template>
      <template #delete>
        <button class="btn btn-danger btn-large">重置</button>
      </template>
    </ValidateFrom>
  </div>

</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import 'bootstrap/dist/css/bootstrap.min.css'
// useRouter定义路由的行为
import { useRouter, useRoute } from 'vue-router'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateFrom from '../components/ValidateForm.vue'
import { PostProps, UploadProps, ResponseType } from '../store'
import Uploader from '@/components/Uploader.vue'
import createMessage from '@/components/createMessage'
import { commonUploadCheck } from '@/hook/helper'
import Editor from '@/components/Editor.vue'
import { Options } from 'easymde'


export default defineComponent({
  name: 'CreatePost',
  components: {
    ValidateInput,
    ValidateFrom,
    Uploader,
    Editor
  },
  setup() {
    //支持EasyMDE编辑器功能
    const editorOptions: Options = {
      spellChecker: false
    }

    // 进行路由跳转
    const router = useRouter()
    // 文字标题验证
    const titleVal = ref('')
    const titleRules: RulesProp = [
      { type: 'requied', message: '文章标题不能为空' },
    ]
    // 文章详情验证
    const contentVal = ref('')
    const contentRules: RulesProp = [
      { type: 'requied', message: '文章详情不能为空' },
    ]

    const store = useStore()

    // easyMDE相关提示信息
    const editorStatus = reactive({
      isValid: true,
      message: ''
    })
    const checkEditor = () => {
      if (contentVal.value.trim() === '') {
        editorStatus.isValid = false
        editorStatus.message = '文章详情不能为空'
      } else {
        editorStatus.isValid = true
        editorStatus.message = ''
      }
    }
    // 编辑
    const route = useRoute()
    const isEditMode = !!route.query.id   // 判断是否是编辑模式 转换boolean类型
    const uploadedData = ref()


    onMounted(() => {

      // 判断是否是编辑状态
      if (isEditMode) {
        store.dispatch('fetchPost', route.query.id).then((rawData: ResponseType<PostProps>) => {
          const currentPost = rawData.data
          if (currentPost.image) {
            uploadedData.value = { data: currentPost.image } // ????? 不明白为什么要这样写
          }
          titleVal.value = currentPost.title
          contentVal.value = currentPost.content || ''
        })
      }
    })


    // 提交
    const onFormSubmit = (result: boolean) => {
      checkEditor()
      if (result && editorStatus.isValid) {
        const { column, _id } = store.state.user
        if (column) {
          const newPost: PostProps = {
            title: titleVal.value,
            content: contentVal.value,
            column,
            author: _id,
            createdAt: new Date().toLocaleString(),
          }
          if (imageId) {
            newPost.image = imageId
          }
          //进一步判断是否是编辑模式 选择性发送数据
          const actionName = isEditMode ? 'updatePost' : 'createPost'
          const sendData = isEditMode ? {
            id: route.query.id,
            payload: newPost
          } : newPost
          console.log(newPost);


          store.dispatch(actionName, sendData).then(() => {
            createMessage('发表文章成功,1S跳到新建文章页面', 'success', 2000)
            setTimeout(() => {
              router.push(`/column/${column}`)
            }, 1000)
          })

        }
      }
    }

    //上传成功
    //拿到图片的回调交给新建文章newPost列表
    let imageId = ''
    const onFileUpload = (rawData: ResponseType<UploadProps>) => {
      if (rawData.data._id) {
        imageId = rawData.data._id
      }
      createMessage(`上传图片的id是${rawData.data._id}`, 'success', 2000)
    }

    // 上传失败
    const onFileUploadedError = (err: ResponseType<UploadProps>) => {
      const msg = err.msg || '上传路径错误'
      createMessage(`上传文件 ${msg}`, 'error', 2000)
    }


    // 删除
    const onFileUploadedDelete = (message: string) => {
      createMessage(message, 'success', 2000)
    }
    return {
      titleVal,
      titleRules,
      contentVal,
      contentRules,
      onFormSubmit,
      commonUploadCheck,
      onFileUpload,
      onFileUploadedError,
      onFileUploadedDelete,
      uploadedData,
      isEditMode,
      editorOptions,
      checkEditor,
      editorStatus
    }
  }

}

)
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.create-post-page .file-upload-container {
  height: 400px;
  cursor: pointer;
  overflow: hidden;
}

.create-post-page .file-upload-container img {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

.uploaded-area {
  position: relative;
}

.uploaded-area:hover h3 {
  display: block;
}

.uploaded-area h3 {
  display: none;
  position: absolute;
  color: #999;
  text-align: center;
  width: 100%;
  top: 50%;
}
</style>
